#include "coreextract.h"
#include <algorithm>

QList<QRect> CoreExtract::getRects(const QList<QPair<QPoint, QPoint>>& line_point_list)
{

    QList<QPair<QPoint, QPoint>> lines = {
        {{0,0}, {10,0}},   // L0
        {{0,0}, {0,5}},    // L1
        {{0,5}, {10,5}},   // L2
        {{3,0}, {3,12}},   // L3
        {{3,12}, {10,12}}, // L4
        {{10,0}, {10,12}}  // L5
    };

    // 提取水平/垂直线段    找交点   生成矩形
    QList<QPoint> horizontal, vertical;
    for (const auto& line : lines) {
        if (line.first.y() == line.second.y()) { // 水平线
            horizontal << line.first << line.second;
        } else if (line.first.x() == line.second.x()) { // 垂直线
            vertical << line.first << line.second;
        }
    }

    // 去重 + 排序
    auto sortUnique = [](QList<QPoint>& list, bool sortX) {
        std::sort(list.begin(), list.end(), [sortX](const QPoint& a, const QPoint& b) {
            return sortX ? a.x() < b.x() : a.y() < b.y();
        });
        auto last = std::unique(list.begin(), list.end());
        list.erase(last, list.end());
    };
    sortUnique(horizontal, false); // 水平线按 y 排序
    sortUnique(vertical, true);    // 垂直线按 x 排序

    // 组合生成矩形
    QList<QRect> rects;
    for (int i = 0; i < vertical.size()-1; ++i) {
    for (int j = 0; j < horizontal.size()-1; ++j) {
    int x1 = vertical[i].x();
    int y1 = horizontal[j].y();
    int x2 = vertical[i+1].x();
    int y2 = horizontal[j+1].y();
    // 计算矩形宽高
    int w = x2 - x1 + 1;
    int h = y2 - y1 + 1;
                // 只添加符合条件的4个矩形（直接在这里过滤）
    bool isTarget =
    // 矩形1: (0,0)-(3,5)
                    (x1 == 0 && y1 == 0 && x2 == 3 && y2 == 5) ||
    // 矩形2: (3,0)-(10,5)
                    (x1 == 3 && y1 == 0 && x2 == 10 && y2 == 5) ||
    // 矩形3: (3,5)-(10,12)
                    (x1 == 3 && y1 == 5 && x2 == 10 && y2 == 12) ;
                if (isTarget) {
    rects << QRect(x1, y1, w, h);
                }
            }
        }
    return rects;


}
